from flask import Flask, jsonify, render_template
import threading
import time
import ft4222
from queue import Queue
import sys

app = Flask(__name__)

# Thread-safe queue for temperature updates
temperature_queue = Queue(maxsize=1)

def get_temp_by_ft4222(ft4222_device):
    """Reads temperature from TMP112 sensor via FT4222 device.

    Args:
        ft4222_device: The FT4222 device instance.

    Returns:
        float: The temperature in Celsius.
    """
    slave_addr = 0x48  # TMP112 I2C address
    reg_addr = 0x00    # TMP112 temperature register

    try:
        # Write the register address to TMP112
        ft4222_device.i2cMaster_Write(slave_addr, bytearray([reg_addr]))
        
        # Read 2 bytes of temperature data from TMP112
        data = ft4222_device.i2cMaster_Read(slave_addr, 2)
        
        # Convert raw data to temperature
        temp = (data[0] << 8 | data[1]) >> 4
        return temp * 0.0625
    except Exception as e:
        print(f"Error during temperature read: {e}")
        return None

def device_service(ft4222_device):
    """Service thread to fetch temperature at regular intervals.

    Args:
        ft4222_device: The FT4222 device instance.
    """
    while True:
        try:
            if ft4222_device is not None:
                temp = get_temp_by_ft4222(ft4222_device)
                if temp is not None:
                    print(f"Temperature: {temp:.2f}°C")
                    
                    # Update thread-safe queue
                    if not temperature_queue.full():
                        temperature_queue.put(temp)
                    else:
                        temperature_queue.get_nowait()  # Remove old value
                        temperature_queue.put(temp)
            else:
                print("FT4222 device is not opened")
        except Exception as e:
            print(f"Error reading temperature in service: {e}")
        time.sleep(5)



@app.route('/')
def home():
    return render_template('index.html')


@app.route('/temperature')
def get_temperature():
    """Endpoint to get the current temperature."""
    if not temperature_queue.empty():
        temp = temperature_queue.get_nowait()
        temperature_queue.put(temp)  # Return to queue for other threads
        return jsonify({"temperature": temp})
    else:
        return jsonify({"error": "Temperature not available"}), 503

def start_web_service():
    """Starts the Flask web service."""
    app.run(port=5000, debug=True, use_reloader=False)

if __name__ == '__main__':

    # FT4222 Device---------------------------------------------------------------------------
    FT4222_Ready = True
    print('Initializing FT4222 device...')
    try:
        # Open FT4222 device
        ft4222_device = ft4222.openByDescription('FT4222 A')
        if ft4222_device is None:
            raise Exception("Failed to open FT4222 device.")
        
        # Initialize I2C Master mode
        ft4222_device.i2cMaster_Init(kbps=100)
        print("I2C Master mode initialized.")
    except Exception as e:
        print(f"Initialization FT4222 error: {e}")
        FT4222_Ready = False

    # RFID Reader Device-----------------------------------------------------------------------



    # ------------------------------------------------------------------------------------------

    # Start the device service thread
    if FT4222_Ready:
        device_thread = threading.Thread(target=device_service, args=[ft4222_device], daemon=True)
        device_thread.start()

    # Start the Flask web service thread
    web_thread = threading.Thread(target=start_web_service, daemon=True)
    web_thread.start()

    # Keep the main thread alive
    if FT4222_Ready:
        device_thread.join()

    web_thread.join()

